<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-09 17:22:41
 * @LastEditors: wangming
 * @LastEditTime: 2022-07-20 14:05:48
 * @Description: file content
-->
<route>
{
  "meta":{
    "title": "权限配置",
    "localism": "sys.permission_set"
  }
}
</route>
<template>
  <div class="role-page">
    <el-row class="pt20">
      <el-col :span="8">
        {{ $t("sys.role_name") }}：{{ formData.name }}
      </el-col>
      <el-col :span="8">
        {{ $t("sys.status") }}：{{ formData.status | roleStatus }}
      </el-col>
      <el-col :span="8">
        {{ $t("sys.remarks") }}：{{ formData.comment }}
      </el-col>
    </el-row>

    <div class="mt10" style="height: 1px"></div>
    <el-divider content-position="left">{{
      $t("sys.permission_set")
    }}</el-divider>

    <el-table
      class="mt10"
      :data="tableData"
      v-loading="tableLoading"
      style="width: 100%"
      current-row-key="id"
      row-key="id"
      default-expand-all
      stripe
      border
    >
      <el-table-column prop="name" :label="$t('sys.menu_name')" width="320">
        <template slot-scope="scope">
          <i
            v-if="scope.row.icon"
            style="font-size: 20px; vertical-align: middle; margin-right: 10px"
            :class="scope.row.icon"
          />
          <span style="position: relative; top: 2px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="pageName" :label="$t('sys.page_name')" width="200">
        <template slot-scope="scope">
          <i
            :title="$t('sys.mobile_page')"
            v-if="scope.row.pageType === 'APP'"
            class="el-icon-mobile-phone mr5"
          ></i>
          <i
            v-if="scope.row.pageType === 'ALL'"
            class="el-icon-monitor mr5"
          ></i>
          {{ scope.row.pageName }}
        </template>
      </el-table-column>
      <el-table-column
        prop="actions"
        :label="$t('sys.accessible_rights')"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <el-checkbox
            v-if="scope.row.type === 'SUB'"
            v-model="scope.row.checked"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
        prop="buttonPermissions"
        :label="$t('sys.operation_authority')"
      >
        <template slot-scope="scope">
          <el-checkbox
            v-model="ele.checked"
            v-for="ele in scope.row.buttonPermissions"
            :key="ele.componentId"
            >{{ ele.alias || ele.name }}</el-checkbox
          >
        </template>
      </el-table-column>
    </el-table>

    <FieldsAuth ref="FieldsAuth" />

    <div class="role-footer">
      <el-button type="primary" @click="submit" :loading="tableLoading">{{
        $t("sys.confirm")
      }}</el-button>
    </div>
  </div>
</template>

<script>
import { arrayToTree } from "@/utils/util";
import { getHmroleInfo } from "@/apis/paas/HmRoleController.js";
import {
  getMenupermissionconfig,
  postMenupermissionconfig,
} from "@/apis/paas/HmMenuPermissionConfigController.js";
import FieldsAuth from "./__components__/FieldsAuth";
import { mapGetters } from "vuex";
export default {
  name: "Role",
  components: {
    FieldsAuth,
  },
  data() {
    return {
      formData: {},
      tableLoading: false,
      tableData: [],
      menuIdList: [],
    };
  },

  computed: {
    ...mapGetters(["MOS_ENABLED"]),
    isNew() {
      return !this.formData.id;
    },
  },

  created() {
    const { id } = this.$route.query;
    this._roleId = id;
    this.initData();
  },

  watch: {
    "$route.query.id"(value) {
      this._roleId = Number(value);
      this.initData();
    },
  },

  methods: {
    async initData() {
      if (!this._roleId) {
        return;
      }
      this.loadMenuData();
      this.loadRoleData();
    },

    async loadMenuData() {
      this.tableLoading = true;
      return getMenupermissionconfig({
        roleId: this._roleId,
      }).then((res) => {
        const data = res
          .filter((i) => {
            return (
              !i.hidden &&
              (!this.MOS_ENABLED ||
                i.pathName !== "organizationPermission-organization")
            );
          })
          .map((item) => {
            if (
              item.type === "SUB" &&
              item.buttonPermissions &&
              item.buttonPermissions.length > 0
            ) {
              item.buttonPermissions = item.buttonPermissions
                .filter((i) => {
                  if (process.env.VUE_APP_ROOT_URL !== "./") {
                    return ![
                      "system_org__user_grant_seat",
                      "system_org__user_cancel_seat",
                    ].includes(i.componentId);
                  } else {
                    return true;
                  }
                })
                .map((button) => {
                  button.checked = !button.checked;
                  return button;
                });
            }
            return item;
          });
        this.tableData = arrayToTree(data, null);
        this.tableLoading = false;
      });
    },

    loadRoleData() {
      getHmroleInfo({
        id: this._roleId,
      }).then((res) => {
        this.formData = {
          ...res,
        };
      });
    },

    handleFieldsAuthClick(row, container) {
      this.$refs.FieldsAuth.open({
        containers: row.containerPermissions,
        containerId: container.componentId,
        roleId: this._roleId,
        menuId: row.id,
        pageId: row.pageId,
        onConfirm: () => {},
      });
    },

    getContainerPermissions(menuId, components) {
      let dataList;
      components.forEach((comp) => {
        const { componentId, componentType } = comp;
        const dataKey = "menu_" + menuId + "_" + componentId;
        const fields = this._containerFieldsMap[dataKey];

        const dataItem = {
          componentId,
          componentType,
        };

        if (fields) {
          dataItem.update = true;
          const hidden = fields
            .filter((item) => item.accessLevel === "Hidden")
            .map((item) => item.fieldCode);
          dataItem.hidden = hidden;
          if (componentType === "Form") {
            const readonly = fields
              .filter((item) => item.accessLevel === "ReadOnly")
              .map((item) => item.fieldCode);
            dataItem.readonly = readonly;
          }
        } else {
          dataItem.update = false;
        }

        if (dataList) {
          dataList.push(dataItem);
        } else {
          dataList = [dataItem];
        }
      });
      return dataList;
    },

    getSelectedMenu(tree = [], list = []) {
      tree.forEach((node) => {
        if (node.type === "SUB" && node.checked) {
          list.push({
            menuId: node.id,
            pageId: node.pageId,
            buttonPermissions: node.buttonPermissions
              .filter((item) => item.checked === false)
              .map((item) => item.componentId),
            // containerPermissions: this.getContainerPermissions(node.id, node.containerPermissions),
            containerPermissions: [],
          });
        } else if (
          node.type === "TOP" &&
          node.children &&
          node.children.length > 0
        ) {
          this.getSelectedMenu(node.children, list);
        }
      });
      return list;
    },

    async submit() {
      this.tableLoading = true;
      this._containerFieldsMap = this.$refs.FieldsAuth.containerFieldsMap;
      const menuPermissionConfigs = this.getSelectedMenu(this.tableData);

      postMenupermissionconfig({
        roleId: this._roleId,
        menuPermissionConfigs,
      })
        .then(() => {
          this.$message.success(this.$t("sys.operation_success"));
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
$toolbar-height: 60px;

.role-page {
  padding-bottom: $toolbar-height;
}

.role-footer {
  background: #fff;
  height: $toolbar-height;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: absolute;
  z-index: 1;
  width: 100%;
  bottom: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 20px;
  box-sizing: border-box;
}

.el-icon-mobile-phone {
  cursor: pointer;
}
</style>
<style lang="scss">
.hamenu {
  position: relative;
  z-index: 2;
}
</style>
